package com.tencent.sr.iris.basic.saas.restapi.station;

import cn.hutool.core.net.URLEncodeUtil;
import com.alibaba.fastjson.JSON;
import com.tencent.sr.iris.basic.saas.common.enums.StationMessageLinkTypeEnum;
import com.tencent.sr.iris.basic.saas.dependency.WxDependency;
import com.tencent.sr.iris.basic.saas.dependency.station.StationMessageDependency;
import com.tencent.sr.iris.basic.saas.interfaces.response.WxQrCodeResponse;
import com.tencent.sr.iris.basic.saas.service.dto.request.StationMessagePreviewRequest;
import com.tencent.sr.iris.basic.saas.service.station.StationMessageService;
import com.tencent.sr.iris.basic.service.interfaces.dto.StationMessageExtInfoDTO;
import com.tencent.sr.iris.basic.service.interfaces.request.GetWxQrCodeRequest;
import com.tencent.sr.iris.basic.service.interfaces.request.station.StationMessageBasicRequest;
import com.tencent.sr.iris.basic.service.interfaces.request.station.StationMessageDetailRequest;
import com.tencent.sr.iris.basic.service.interfaces.request.station.StationMessagePageRequest;
import com.tencent.sr.iris.basic.service.interfaces.request.station.StationMessageSaveRequest;
import com.tencent.sr.iris.basic.service.interfaces.request.station.StationMessageUpdateRequest;
import com.tencent.sr.iris.basic.service.interfaces.response.GetWxQrCodeResponse;
import com.tencent.sr.iris.basic.service.interfaces.response.QrCodeBase64Response;
import com.tencent.sr.iris.basic.service.interfaces.response.station.StationMessageDetailResponse;
import com.tencent.sr.iris.basic.service.interfaces.response.station.StationMessagePageResponse;
import com.tencent.sr.rmall.common.primitive.HttpResult;
import com.tencent.sr.rmall.common.request.PaginationRequest;
import com.tencent.sr.rmall.common.response.PaginationResponse;
import com.tencent.sr.rmall.springbootstarter.authtoken.localbean.AppUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Resource;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@Api("站内信关接口")
@RequestMapping("/iris/basic/saas/v1/station/message")
public class StationMessageController {
    @Resource
    private StationMessageService stationMessageService;
    @Resource
    private WxDependency wxDependency;

    @Value("${miniprogram.env:release}")
    private String env;
    @Resource
    private AppUser appUser;

    @PostMapping("/page")
    @ApiOperation("站内信分页查询")
    public HttpResult<PaginationResponse<StationMessagePageResponse>> page(
            @Valid @RequestBody PaginationRequest<StationMessagePageRequest> request) {
        return HttpResult.succ(stationMessageService.page(request));
    }

    @PostMapping("/insert")
    @ApiOperation("插入站内信")
    public HttpResult<Boolean> insert(@Valid @RequestBody StationMessageSaveRequest request) {
        request.setCreatorUid(appUser.getUid());
        request.setUpdateUid(appUser.getUid());
        return HttpResult.succ(stationMessageService.insert(request));
    }

    @PostMapping("/detail")
    @ApiOperation("查询站内信详情")
    public HttpResult<StationMessageDetailResponse> detail(@Valid @RequestBody StationMessageBasicRequest request) {
        return HttpResult.succ(stationMessageService.detail(request));
    }

    @PostMapping("/delete")
    @ApiOperation("删除站内信")
    public HttpResult<Boolean> delete(@Valid @RequestBody StationMessageBasicRequest request) {
        request.setUpdateUid(appUser.getUid());
        return HttpResult.succ(stationMessageService.delete(request));
    }

    @PostMapping("/publish")
    @ApiOperation("站内信发布生效")
    public HttpResult<Boolean> publish(@Valid @RequestBody StationMessageBasicRequest request) {
        request.setUpdateUid(appUser.getUid());
        return HttpResult.succ(stationMessageService.publish(request));
    }

    @PostMapping("/update")
    @ApiOperation("更新站内信")
    public HttpResult<Boolean> update(@Valid @RequestBody StationMessageUpdateRequest request) {
        request.setUpdateUid(appUser.getUid());
        return HttpResult.succ(stationMessageService.update(request));
    }


    @Deprecated
    @ApiOperation("预览站内信")
    @PostMapping("/previewCode")
    HttpResult<QrCodeBase64Response> preview(@Valid @RequestBody StationMessagePreviewRequest request) {
        String id = request.getId();
        Byte linkType = request.getLinkType();
        String messageId = request.getMessageId();
        GetWxQrCodeRequest qrCodeRequest = new GetWxQrCodeRequest();
        String envVersion = Optional.ofNullable(request.getEnvVersion()).orElse(env);
        qrCodeRequest.setEnvVersion(envVersion);
        if (linkType.equals(StationMessageLinkTypeEnum.GOODS.getCode())) {
            qrCodeRequest.setPage("pages/goods/detail/detail");
            qrCodeRequest.setScene("goodsId=" + id);
            return HttpResult.succ(wxDependency.getWxQrCodeBase64(qrCodeRequest));
        }

        StationMessageDetailRequest stationMessageRequest = new StationMessageDetailRequest();
        stationMessageRequest.setMessageId(messageId);
        StationMessageDetailResponse response = stationMessageService.detailByMessageId(stationMessageRequest);
        if (linkType.equals(StationMessageLinkTypeEnum.ACTIVITY.getCode())) {
            String extInfo = response.getExtInfo();
            String base64 = "";
            try {
                base64 = readInputStream(extInfo);
            } catch (Exception e) {
                log.error("get Base64 error:{}", e.getMessage());
            }
            QrCodeBase64Response result = new QrCodeBase64Response();
            result.setSunCodeImgBase64(base64);
            return HttpResult.succ(result);
        }

        if (linkType.equals(StationMessageLinkTypeEnum.IRIS_ACTIVITY.getCode()) ) {
            String extInfo = response.getExtInfo();
            String base64 = "";
            try {
                StationMessageExtInfoDTO stationMessageExtInfoDTO = JSON.parseObject(extInfo,
                        StationMessageExtInfoDTO.class);
                base64 = readInputStream(stationMessageExtInfoDTO.getQrCodePicUrl());
            } catch (Exception e) {
                log.error("get Base64 error:{}", e.getMessage());
            }
            QrCodeBase64Response result = new QrCodeBase64Response();
            result.setSunCodeImgBase64(base64);
            return HttpResult.succ(result);
        }

        if (linkType.equals(StationMessageLinkTypeEnum.GROUP.getCode())) {
            String link = response.getLink();
            if (StringUtils.isBlank(link)) {
                return HttpResult.fail("link为空");
            }

            String scene = null;
            try {
                scene = "url=" + URLEncoder.encode("https://" + link, StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                log.error("urlEncode error, link:{}", link, e);
                return HttpResult.fail("link ecode失败");
            }
            String page = "pages/h5/index";
            qrCodeRequest.setPage(page);
            qrCodeRequest.setScene(scene);
            return HttpResult.succ(wxDependency.getWxQrCodeBase64(qrCodeRequest));
        }
        return HttpResult.fail("不支持的linkType类型");
    }

    public String readInputStream(String path) throws Exception {
        if (StringUtils.isBlank(path)) {
            return "";
        }

        //new一个URL对象
        URL url = new URL(path);
        //打开链接
        URLConnection conn = url.openConnection();
        //超时响应时间为5秒
        conn.setConnectTimeout(5 * 1000);
        //通过输入流获取图片数据
        InputStream inStream = conn.getInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[4096];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        byte[] data = outStream.toByteArray();
        String base64 = Base64.getEncoder().encodeToString(data);
        outStream.close();
        return base64;
    }


}
